import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:happy_around_us/Pages/ImagePageView.dart';

class ImagePageView2 extends StatefulWidget {
  const ImagePageView2({Key? key}) : super(key: key);

  @override
  State createState() => _ImagePageView2State();
}

class _ImagePageView2State extends State<ImagePageView2> {
  late PageController _pageController;
  int currentPageIndex = 0;
  List<UserModel> data = [
    UserModel('咕呱咕呱'),
    UserModel('咕呱咕呱1'),
    UserModel('咕呱咕呱2'),
    UserModel('咕呱咕呱3'),
    UserModel('咕呱咕呱4'),
    UserModel('咕呱咕呱5'),
    UserModel('咕呱咕呱6'),
  ];

  @override
  void initState() {
    super.initState();

    _pageController = PageController(initialPage: 0);
    _pageController.addListener(_onPageScroll);
  }

  void _onPageScroll() {
    final pageIndex = _pageController.page?.round();
    if (pageIndex != null && pageIndex != currentPageIndex) {
      currentPageIndex = pageIndex;

      //  自动加载
      if (currentPageIndex == data.length - 2) {
        onLoadData();
      }
    }
  }

  /**
   * 下拉刷新方法,为list重新赋值
   */
  Future<void> _onRefresh() async {
    await Future.delayed(Duration(seconds: 1), () {
      print('refresh');
      setState(() {});
    });
  }

  /// 视频数据 API请求
  Future<void> onLoadData() async {
    // 延迟200ms 模拟网络请求
    await Future.delayed(const Duration(milliseconds: 200));
    print('=========> loadData');
    setState(() {
      data.add(UserModel('咕呱咕呱${data.length} 新增'));
      data.add(UserModel('咕呱咕呱${data.length} 新增'));
    });
  }

  @override
  void dispose() {
    _pageController.removeListener(_onPageScroll);
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    return Scaffold(
      resizeToAvoidBottomInset: false, //很重要,不加键盘弹出视频会被挤压
      body: Stack(
        children: [
          refreshIndicator(size),
        ],
      ),
    );
  }

  Widget refreshIndicator(Size size) {
    return RefreshIndicator(
      onRefresh: _onRefresh,
      child: pageView(size),
    );
  }

  Widget pageView(Size size) {
    return PageView.builder(
      scrollDirection: Axis.vertical,
      controller: _pageController,
      onPageChanged: (currentPage) {
        //页面发生改变的回调
      },
      itemBuilder: (context, index) {
        return ImageFullPage(size: size, model: data[index]);
      },
    );
  }
}
